package PrjHttpUtils

import (
	"dgo/goutils/utils"
	"fmt"
	"net/http"
	"os"
)

var (
	Config_UploadFile_Root               string                                                        = ""
	Config_uploadFile_MaxSize            int64                                                         = 1024 * 1024 * 10
	Config_UploadFile_Exists_ProcessFlag int                                                           = 0 //0: 重命名, 1: 覆盖
	Config_UploadFileSucc_CallBack       func(filename string, w http.ResponseWriter, r *http.Request) = nil
)

func UploadFile(w http.ResponseWriter, r *http.Request) {
	err := r.ParseMultipartForm(Config_uploadFile_MaxSize)
	if err != nil {
		http.Error(w, fmt.Sprintf("解析MultiPartForm出现异常:%s", err.Error()), 503)
		return
	}

	strFileNames := r.MultipartForm.Value["filename"]

	files := r.MultipartForm.File["upfile"]
	if len(files) == 0 {
		files = r.MultipartForm.File["file"]
		if len(files) == 0 {
			http.Error(w, fmt.Sprintf("没有指定上传文件(%s)参数", "upfile"), 503)
			return
		}
	}
	tmpFile, err1 := files[0].Open()
	if err1 != nil {
		http.Error(w, fmt.Sprintf("打开文件出现异常:%s", err.Error()), 503)
		return
	}
	strFileName := ""
	if len(strFileNames) == 0 {
		strFileName = os.TempDir() + fmt.Sprintf("%s.tmp", utils.RandHexString(24))
	} else {
		strFileName = Config_UploadFile_Root + strFileNames[0]
		utils.ForceCreateFilePath(strFileName)
	}

	if utils.FileIsExists(strFileName) {
		existsflagstr := r.URL.Query().Get("existsflag")
		existsflag := Config_UploadFile_Exists_ProcessFlag

		if len(existsflagstr) > 0 {
			existsflag = utils.StrToIntDef(existsflagstr, 0)
		}

		if existsflag == 0 { // 重命名
			strFileName = utils.NewFileNameIfExistsThenIncSN(strFileName)
		}

	}

	_, err = utils.NewFileFromReader(strFileName, tmpFile)
	if err != nil {
		http.Error(w, fmt.Sprintf("存储文件异常:%s", err.Error()), 503)
		return
	}

	if Config_UploadFileSucc_CallBack != nil {
		Config_UploadFileSucc_CallBack(strFileName, w, r)
	} else {
		w.WriteHeader(200)
	}
}

func RegisterUploadFileHandle() {
	HandleFunc("/api/file/upload", UploadFile)
}
